package com.qtenv.datasync.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.qtenv.datasync.base.BaseJobHandler;
import com.qtenv.datasync.constant.AppConstants;
import com.qtenv.datasync.service.entity.DataPerfect;
import com.qtenv.datasync.service.service.DataPerfectService;
import com.qtenv.datasync.worker.chuanyi.CYDataSyncWorker;
import com.qtenv.datasync.worker.degao.DGDataSyncWorker;
import com.qtenv.datasync.worker.huizhong.HZDataSyncWorker;
import com.qtenv.datasync.worker.tuoanxin.TAXDataSyncWorker;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName SyncDataJob
 * @Author CBL
 * @Date 2022/4/6 16:31
 **/
@Slf4j
@Component
public class SyncDataJob extends BaseJobHandler {
    @Autowired
    private CYDataSyncWorker cyDataSyncWorker;

    @Autowired
    private DGDataSyncWorker dgDataSyncWorker;

    @Autowired
    private HZDataSyncWorker hzDataSyncWorker;

    @Autowired
    private TAXDataSyncWorker taxDataSyncWorker;

    @Autowired
    private DataPerfectService dataPerfectService;

    private final String TENANT_KEY = "tenant";
    private final String SHEETS_CODE_KEY = "sheetsCode";
    private final String START_KEY = "start";
    private final String START_SUFFIX = " 00:00:00";
    private final String END_KEY = "end";
    private final String END_SUFFIX = " 23:59:59";

    /**
    * @Description: 同步大表档案
    * @date: 2025/3/24 14:08
    * @author: zt
    */
    @XxlJob("SyncTerminalDataInJC")
    public ReturnT<String> SyncTerminalDataInJC(String param) {
        log.info("==========开始同步档案==========");
        this.syncTerminalDataInJC(param);
        log.info("==========同步档案完成==========");
        return ReturnT.SUCCESS;
    }

    /**
     * @Description: 同步大表档案历史数据
     * @date: 2025/3/24 14:08
     * @author: zt
     */
    @XxlJob("SyncTerminalHistoryDataInJC")
    public ReturnT<String> SyncTerminalDbHistoryDataInJC(String param) {
        log.info("==========开始同步档案==========");
        this.syncTerminalDbHistoryDataInJC(param);
        log.info("==========同步档案完成==========");
        return ReturnT.SUCCESS;
    }


    @XxlJob("SyncRealTimeData")
    public ReturnT<String> SyncRealTimeData(String param) {
        log.info("==========开始同步实时数据==========");
        this.synRealTimeData(param);
        log.info("==========同步实时数据完成==========");
        return ReturnT.SUCCESS;
    }

    @XxlJob("SyncTodayData")
    public ReturnT<String> SyncTodayData(String param) {
        log.info("==========开始同步当天数据==========");
        String startTime = LocalDate.now().toString();
        String endTime = LocalDate.now().toString();
        this.synData(param, startTime, endTime);
        log.info("==========当天数据同步完成==========");
        return ReturnT.SUCCESS;
    }

    @XxlJob("SyncYesterdayData")
    public ReturnT<String> SyncYesterdayData(String param) {
        log.info("==========开始同步昨天数据==========");
        String startTime = LocalDate.now().minusDays(1L).toString();
        String endTime = LocalDate.now().minusDays(1L).toString();
        this.synData(param, startTime, endTime);
        log.info("==========昨天数据同步完成==========");
        return ReturnT.SUCCESS;
    }

    @XxlJob("SyncTheDayBeforeYesterdayData")
    public ReturnT<String> SyncTheDayBeforeYesterdayData(String param) {
        log.info("==========开始同步前天数据==========");
        String startTime = LocalDate.now().minusDays(2L).toString();
        String endTime = LocalDate.now().minusDays(2L).toString();
        this.synData(param, startTime, endTime);
        log.info("==========前天数据同步完成==========");
        return ReturnT.SUCCESS;
    }

    @XxlJob("SyncDataPerfect")
    public ReturnT<String> SyncDataPerfect(String param) {
        log.info("==========开始执行数据完整性任务==========");
        List<DataPerfect> dataPerfectList = dataPerfectService.list(new QueryWrapper<DataPerfect>().eq("refine", 0).lt("repull_count", AppConstants.DATA_PERFECT_COUNT));
        if (CollectionUtil.isNotEmpty(dataPerfectList)) {
            // 先按租户分组
            Map<String, List<DataPerfect>> tenantListMap = dataPerfectList.stream().collect(Collectors.groupingBy(DataPerfect::getTenantId));
            tenantListMap.forEach((tenantId, dpList) -> {
                // 再按时间分组
                Map<String, List<DataPerfect>> timeListMap = dpList.stream().collect(Collectors.groupingBy(DataPerfect::getDataOutageTime));
                timeListMap.forEach((outageTime, missingList) -> {
                    System.out.println("缺失数据日期：" + outageTime);
                    List<String> dgTerminalList = missingList.stream().filter(item -> item.getTerminalID().substring(6, 10).equals("1002")).map(item -> item.getTerminalID().substring(10)).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(dgTerminalList)) {
                        dgDataSyncWorker.syncTerminalHistoryData(tenantId, dgTerminalList, outageTime, outageTime);
                    }
                    List<String> hzTerminalList = missingList.stream().filter(item -> item.getTerminalID().substring(6, 10).equals("1004")).map(item -> item.getTerminalID()).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(hzTerminalList)) {
                        hzDataSyncWorker.syncTerminalHistoryData(tenantId, hzTerminalList, outageTime, outageTime);
                    }
                    List<String> cyTerminalList = missingList.stream().filter(item -> item.getTerminalID().substring(6, 10).equals("1011")).map(item -> item.getTerminalID()).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(cyTerminalList)) {
                        cyDataSyncWorker.syncTerminalHistoryData(tenantId, cyTerminalList, outageTime, outageTime);
                    }
                    List<String> taxTerminalList = missingList.stream().filter(item -> item.getTerminalID().substring(6, 10).equals("1005")).map(item -> item.getTerminalID()).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(taxTerminalList)) {
                        taxDataSyncWorker.syncTerminalHistoryData(tenantId, taxTerminalList, outageTime, outageTime);
                    }
                });
            });
            // 重拉次数加1
            dataPerfectService.update(new UpdateWrapper<DataPerfect>().setSql("repull_count=repull_count+1").eq("refine", 0).lt("repull_count", AppConstants.DATA_PERFECT_COUNT));
//             重拉次数超过30次，则视为无数据，更新refine状态，不再继续拉取数据
//            dataPerfectService.update(new UpdateWrapper<DataPerfect>().setSql("refine=1").ge("repull_count", 30));
        }

        log.info("==========数据完整性任务执行完成==========");
        return ReturnT.SUCCESS;
    }

    public void synData(String param, String defaultStartTime, String defaultEndTime) {
        Map<String, Object> paramMap = this.getParamMap(param);
        String tenantId = MapUtil.getStr(paramMap, TENANT_KEY);
        String start = MapUtil.getStr(paramMap, START_KEY);
        String end = MapUtil.getStr(paramMap, END_KEY);
        String startTime = (start == null ? defaultStartTime : start);
        startTime += START_SUFFIX;
        String endTime = (end == null ? defaultEndTime : end);
        endTime += END_SUFFIX;
        // 川仪
        cyDataSyncWorker.syncTerminalHistoryData(AppConstants.CY_SUPPLIER_ID,tenantId,startTime,endTime);
        // 德高
        dgDataSyncWorker.syncTerminalHistoryData(AppConstants.DG_SUPPLIER_ID,tenantId,startTime,endTime);
        // 汇中
        hzDataSyncWorker.syncTerminalHistoryData(AppConstants.HZ_SUPPLIER_ID,tenantId,startTime,endTime);
        // 拓安信
        taxDataSyncWorker.syncTerminalHistoryData(AppConstants.TAX_SUPPLIER_ID,tenantId,startTime,endTime);
    }

    public void synRealTimeData(String param) {
        Map<String, Object> paramMap = this.getParamMap(param);
        String tenantId = MapUtil.getStr(paramMap, TENANT_KEY);
        // 川仪
        cyDataSyncWorker.syncTerminalHistoryData(AppConstants.CY_SUPPLIER_ID,tenantId);
        // 德高
        dgDataSyncWorker.syncTerminalHistoryData(AppConstants.DG_SUPPLIER_ID,tenantId);
        // 汇中
        hzDataSyncWorker.syncTerminalHistoryData(AppConstants.HZ_SUPPLIER_ID,tenantId);
        // 拓安信
        taxDataSyncWorker.syncTerminalHistoryData(AppConstants.TAX_SUPPLIER_ID,tenantId);
    }


    /*同步德高集抄平台数据到漏损控制系统START*/

    public void syncTerminalDataInJC(String param){
        Map<String, Object> paramMap = this.getParamMap(param);
        String sheetsCode = MapUtil.getStr(paramMap, SHEETS_CODE_KEY);
        String tenantId = MapUtil.getStr(paramMap, TENANT_KEY);
        dgDataSyncWorker.syncTerminalDataInJC(AppConstants.DG_SUPPLIER_ID,tenantId,sheetsCode);
    }

    public void syncTerminalDbHistoryDataInJC(String param){
        Map<String, Object> paramMap = this.getParamMap(param);
        String tenantId = MapUtil.getStr(paramMap, TENANT_KEY);
        dgDataSyncWorker.syncTerminalDbHistoryDataInJC(AppConstants.DG_SUPPLIER_ID,tenantId);
    }

    /*同步德高集抄平台数据到漏损控制系统END*/

}
